import { getGuid } from '../../utils/getDefaultValue'
import { DateHelper } from '../DateHelper'
import { OrderTable, OutOfStockTable, stocks } from './TableStore'

export class GroupTableHelper {
  constructor (data = stocks, groupTable = OrderTable) {
    this.renderTable = groupTable.filter((item) => item.hidden !== true)
    this.columnCount = this.renderTable.length
    this.originTable = groupTable
    this.primaryCol = groupTable.find(item => item.primaryKey)
    this.primaryKey = this.primaryCol.col
    this.data = data
    this._filterGroupData(data)
    this.groupIdSet = new Set()
    this.groupIds = []
    /// 根据初始数据 进行初始化
    this.groupData.forEach((item) => {
      if (!this.groupIdSet.has(item[this.primaryKey])) {
        this.groupIdSet.add(item[this.primaryKey])
        this.groupIds.push(item[this.primaryKey])
      }
    })
    /// 初始化
    // this.groupIds = Array.from(this.groupIdSet).sort()
    this.newGroupData = []
  }

  /// 过滤数据
  _filterGroupData (data) {
    var idSet = new Set()
    var groupData = []
    data.forEach((item) => {
      var id = item[this.primaryKey]
      if (!idSet.has(id)) {
        idSet.add(id)
        var itemData = {
          [this.primaryKey]: id
        }
        this.originTable.forEach((column) => {
          if (!column.primaryKey) {
            itemData[column.col] = item[column.col]
          }
        })
        groupData.push(itemData)
      } else {
        console.log(item)
      }
    })
    groupData.sort((a, b) => {
      var aKey = a.customer_name + a.tc_oeb01 + a.material
      var bKey = b.customer_name + b.tc_oeb01 + b.material
      return aKey.localeCompare(bKey)
    })
    this.groupData = groupData
  }

  insertRow (rowIndex, dir = 'prev') {
    var rowId = getGuid()
    var key = this.primaryKey
    this.newGroupData.unshift({
      rowId: rowId,
      [ key ]: rowId
    })
    this.groupIdSet.add(rowId)
    this.groupIds.splice(dir === 'prev' ? rowIndex : rowIndex + 1, 0, rowId)
  }

  getGroupHeaderValue (colIndex) {
    return {
      width: this.renderTable[colIndex].width,
      value: this.renderTable[colIndex].name,
      editable: false,
      align: this.renderTable[colIndex].textAlign
    }
  }

  getGroupCellValue (rowIndex, colIndex) {
    var rowId = this.groupIds[rowIndex]
    var newGroupHeader = this.newGroupData.find((item) => item.rowId === rowId)
    var groupHeader = this.groupData.find((item) => item[this.primaryKey] === rowId)
    var key = this.renderTable[colIndex].col
    var editable = this.renderTable[colIndex].editable
    var clickable = this.renderTable[colIndex].clickable
    var popup = this.renderTable[colIndex].popup
    var valueRender = this.renderTable[colIndex].valueRender
    var align = this.renderTable[colIndex].textAlign

    if (newGroupHeader) {
      return {
        value: newGroupHeader[key],
        editable: editable,
        style: editable ? 0 : undefined,
        clickable: clickable,
        align: align
      }
    } else if (groupHeader) {
      return {
        item: groupHeader,
        value: groupHeader[key],
        valueRender: valueRender,
        editable: false,
        align: align,
        popup: popup,
        key: key
      }
    } else {
      return {
        value: '',
        editable: false,
        align: align
      }
    }
  }
}

export class TableHelper {
  constructor (data = stocks, table = OutOfStockTable) {
    this.primaryCol = table.find(item => item.primaryKey)
    this.foreignCol = table.find(item => item.foreignKey)
    this.valueCol = table.find(item => item.isValue)
    /// date - 新增列的表头是GUID
    this.primaryKey = this.primaryCol.col
    /// orderId - 新增数据的日期是GUID
    this.foreignKey = this.foreignCol.col
    /// quantity
    this.valueKey = this.valueCol.col
    /// 根据初始数据 进行初始化
    this.dateHelper = new DateHelper()
    /// 记录总的列数 包括新增的列 - 注意 只是初始化的时候没有新增列的数据
    this.columnCount = this.dateHelper.dateList.length
    this.data = data
    this.table = table
    this.newData = []
    this.dataMap = {}
    this.deleteData = []
  }

  getDataMap () {
    this.data.forEach((item) => {
      this.dataMap[item[this.primaryKey] + ',' + item[this.foreignKey]] = item
    })
  }

  findDataItem (rowId, columnId) {
    return this.dataMap[columnId + ',' + rowId]
  }

  getHeaderStyle (cellValue) {
    var style
    var date = new Date(cellValue)
    var day = date.getDay()
    if (day === 6 || day === 0) style = 1
    return style
  }

  getHeaderValue (colIndex) {
    var header = this.dateHelper.dateList[colIndex]
    return {
      date: header.date,
      value: header.title,
      isWeek: header.isWeek,
      editable: true,
      width: 50,
      style: this.getHeaderStyle(header.value)
    }
  }

  changePrimaryValue (data, newValue, oldValue) {
    data.forEach((item) => {
      if (item[this.primaryCol.col] === oldValue) {
        item[this.primaryCol.col] = newValue
        /// 标记已经修改
        item.changed = true
      }
    })
    this.data = data
    this.primarySet.clear()
    data.forEach((item) => {
      this.primarySet.add(item[this.primaryCol.col])
    })
    console.log(Array.from(this.primarySet).sort())
  }
}

export class SheetHelper {
  constructor ({
    headerRowCount = 2,
    data = []
  }) {
    this.groupHelper = new GroupTableHelper(data)
    this.helper = new TableHelper(data)
    this.headerRowCount = headerRowCount
  }

  get data () {
    return this.helper.data || []
  }

  get offset () {
    return {
      ri: this.headerRowCount,
      ci: this.groupHelper.columnCount
    }
  }

  get rowCount () {
    return this.headerRowCount + this.groupHelper.groupIds.length
  }

  get columnCount () {
    return this.groupHelper.columnCount + this.helper.dateHelper.dateList.length
  }

  deleteRow (rowIndex) {
    if (rowIndex < this.headerRowCount) {
      return false
    }
    var row = rowIndex - this.headerRowCount
    var rowId = this.groupHelper.groupIds[row]
    /// 新增行可删除
    var newGroupData = this.groupHelper.newGroupData.find((item) => item.rowId === rowId)
    if (!newGroupData) return

    this.groupHelper.groupIds.splice(row, 1)
    this.groupHelper.groupIdSet.delete(rowId)
    this.groupHelper.newGroupData = this.groupHelper.newGroupData.filter((item) => item.rowId !== rowId)
    this.helper.newData = this.helper.newData.filter((item) => item.rowId !== rowId)
    var data = this.helper.data
    var newData = data.filter((item) => item[this.helper.foreignKey] !== rowId)
    var deleteData = data.filter((item) => item[this.helper.foreignKey] === rowId)
    this.helper.data = newData
    this.groupHelper.data = newData
    this.helper.deleteData = this.helper.deleteData.concat(deleteData)
    return true
  }

  insertRow (rowIndex, dir) {
    this.groupHelper.insertRow(rowIndex, dir)
  }

  insertGroupRows (rowIndex, rows) {
    this.groupHelper.groupIds.splice(rowIndex, 0, ...rows.map((row) => row.rowId))
    this.groupHelper.newGroupData = this.groupHelper.newGroupData.concat(rows)
  }

  updateGroupValue (rowIndex, value) {
    var rowId = this.groupHelper.groupIds[rowIndex]
    var index = this.groupHelper.newGroupData.findIndex((item) => item.rowId === rowId)
    if (index !== -1) {
      var newGroupHeader = this.groupHelper.newGroupData[index]
      var newItem = {
        ...newGroupHeader,
        ...value,
        rowId: rowId,
        changed: true
      }
      this.groupHelper.newGroupData[index] = newItem
      return true
    } else {
      var data = this.helper.data.map((item) => {
        if (item[this.helper.foreignKey] === rowId) {
          item = {
            ...item,
            ...value,
            changed: true
          }
          item.changed = true
        }
        return item
      })
      this.helper.data = data
      this.groupHelper.data = data
    }
    return false
  }

  updateGroupCellValue (rowIndex, colIndex, value) {
    var rowId = this.groupHelper.groupIds[rowIndex]
    var newGroupHeader = this.groupHelper.newGroupData.find((item) => item.rowId === rowId)
    var key = this.groupHelper.renderTable[colIndex].col
    if (newGroupHeader) {
      newGroupHeader[key] = value
      return true
    } else {
      this.helper.data.forEach((item) => {
        if (item[this.helper.foreignKey] === rowId) {
          item[key] = value
          item.changed = true
        }
      })
      this.groupHelper.data = this.helper.data
    }
    return false
  }

  updateCellValue (rowIndex, colIndex, value) {
    var columnId = this.helper.dateHelper.dateList[colIndex].date
    var rowId = this.groupHelper.groupIds[rowIndex]
    var newGroupHeader = this.groupHelper.newGroupData.find((item) => item.rowId === rowId)

    if (newGroupHeader) {
      var newItem = this.helper.newData.find((item) => item.columnId === columnId && item.rowId === rowId)
      if (newItem) {
        newItem[this.helper.valueKey] = value
      } else {
        this.helper.newData.unshift({
          rowId: rowId,
          columnId: columnId,
          id: getGuid(),
          [this.helper.valueKey]: value
        })
      }
      return true
    }

    var valItem = this.helper.data.find((item) => {
      return item[this.helper.primaryKey] === columnId && item[this.helper.foreignKey] === rowId
    })

    if (valItem) {
      valItem.changed = true
      valItem[this.helper.valueKey] = value
    } else {
      var groupHeader = this.groupHelper.groupData.find((item) => item[this.helper.foreignKey] === rowId)
      this.helper.data.unshift({
        changed: true,
        id: getGuid(),
        ...groupHeader,
        [this.helper.valueKey]: value,
        [this.helper.primaryKey]: columnId
      })
    }
    return false
  }

  getGroupCellValue (rowIndex, colIndex) {
    return this.groupHelper.getGroupCellValue(rowIndex, colIndex)
  }

  getGroupHeaderValue (colIndex) {
    return this.groupHelper.getGroupHeaderValue(colIndex)
  }

  getHeaderValue (colIndex) {
    return this.helper.getHeaderValue(colIndex)
  }

  getCellValue (rowIndex, colIndex) {
    var columnId = this.helper.dateHelper.dateList[colIndex].date
    var rowId = this.groupHelper.groupIds[rowIndex]
    var newGroupHeader = this.groupHelper.newGroupData.find((item) => item.rowId === rowId)

    if (newGroupHeader) {
      var newItem = this.helper.newData.find((item) => item.columnId === columnId && item.rowId === rowId)
      if (newItem) {
        return {
          value: newItem[this.helper.valueKey] || '',
          editable: true,
          style: 0
        }
      } else {
        return {
          value: '',
          editable: true,
          style: 0
        }
      }
    }

    var valItem = this.helper.findDataItem(rowId, columnId)

    var style = this.helper.getHeaderStyle(columnId)

    if (valItem) {
      return {
        value: valItem[this.helper.valueKey] || '',
        editable: true,
        columnId,
        rowId,
        style
      }
    } else {
      return {
        value: '',
        editable: true,
        columnId,
        rowId,
        style
      }
    }
  }

  clear () {
    this.helper.newData = []
  }

  getAllNewData () {
    var newData = []
    this.helper.newData.forEach((item) => {
      var rowId = item.rowId
      var newGroupHeader = this.groupHelper.newGroupData.find((item) => item.rowId === rowId)
      var itemData = {
        id: item.id,
        rowId: item.rowId,
        columnId: item.columnId,
        [this.helper.valueKey]: item[this.helper.valueKey]
      }

      itemData[this.helper.primaryKey] = item.columnId

      if (newGroupHeader) {
        this.groupHelper.renderTable.map((item) => {
          var key = item.col
          itemData[key] = newGroupHeader[key]
        })
      } else {
        var groupHeader = this.groupHelper.groupData.find((item) => item[this.helper.foreignKey] === rowId)
        this.groupHelper.renderTable.map((item) => {
          var key = item.col
          itemData[key] = groupHeader[key]
        })
      }

      newData.push(itemData)
    })

    return newData
  }
}
